package com.archeanx.libx.util

import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.constant.RefreshState

const val LOAD_NO = 121
const val LOAD_ERROR = 122
const val LOAD_SUCCESS = 123


fun SmartRefreshLayout?.loadSuccess(pageIndex: Int = 0, pageCount: Int = 0) {
    this ?: return
    if (pageIndex == 0 && pageCount == 0) {
        if (this.isRefreshing) {
            finishRefresh()
        }
        if (this.isLoading) {
            finishLoadMore()
        }
    } else {
        if (this.isRefreshing) {
            if (pageIndex >= pageCount) {
                finishRefreshWithNoMoreData()
            } else {
                finishRefresh()
            }
        }
        if (this.isLoading) {
            if (pageIndex >= pageCount) {
                finishLoadMoreWithNoMoreData()
            } else {
                finishLoadMore()
            }
        }
    }
}

/**
 * 加载失败
 */
fun SmartRefreshLayout?.loadError() {
    this ?: return
    stopRefrshLoad(LOAD_ERROR)
}

/**
 * 没有更多数据
 */
fun SmartRefreshLayout?.loadNoData() {
    this ?: return
    stopRefrshLoad(LOAD_NO)
}


/**
 * 刷新时，允许加载更多
 */
fun SmartRefreshLayout?.onRefreshStatus() {
    this ?: return
    setNoMoreData(false)
}


/**
 * 立即停止刷新加载
 */
fun SmartRefreshLayout?.stopRefrshLoad(
        loadStatus: Int,
        refreshDelayed: Int = 300,
        loadDelayed: Int = 300
) {
    this ?: return

    if (state == RefreshState.Refreshing) {
        finishRefresh(refreshDelayed)
    }
    if (state == RefreshState.Loading) {
        when (loadStatus) {
            LOAD_NO -> finishLoadMore(loadDelayed, true, true)
            LOAD_ERROR -> finishLoadMore(loadDelayed, false, false)
            LOAD_SUCCESS -> finishLoadMore(loadDelayed, true, false)
        }
    }
}

/**
 * 禁用刷新加载 带阻尼效果
 */
fun SmartRefreshLayout?.dampingStyle() {
    this ?: return
    this.setEnableLoadMore(false)
    this.setEnableRefresh(false)
    this.setEnableOverScrollBounce(true)
    this.setEnableOverScrollDrag(true)
    this.setEnablePureScrollMode(true)
}

/**
 * 禁用加载更多 带阻尼效果
 */
fun SmartRefreshLayout?.dampingRefreshStyle() {
    this ?: return
    this.setEnableLoadMore(false)
    this.setEnableRefresh(true)
    this.setEnableOverScrollBounce(true)
    this.setEnableOverScrollDrag(true)
    this.setEnablePureScrollMode(true)
}